import java.util.Arrays;

public class ArrayList implements IList {

    public int[] array;
    public int usedSize;
    public static final int DEFAULT_CAPACITY = 5;

    public ArrayList() {
         array = new int[DEFAULT_CAPACITY];
    }

    //判空
    private boolean isFull() {
        return array.length == usedSize;
    }

    //扩容
    private void grow() {
        array = Arrays.copyOf(array, 2*array.length);
    }


    //检查下标是否合法
    private boolean checkPos(int pos) {
        if(pos < 0 || pos > usedSize) {
            return true;
        }
        return false;
    }


    //判空
    public boolean isEmpty() {
        return usedSize == 0;
    }


    public void add(int data) {
        if(isFull()) {
            grow();
        }

        array[usedSize++] = data;

    }

    public void add(int pos, int data) {
        checkPos(pos);
        if(isFull()) {
            grow();
        }

        for(int i = usedSize - 1; i <= pos; i--) {
            array[i + 1] = array[i];
        }
        array[pos] = data;
        usedSize++;
    }

    //判断顺序表中是否包含data这个元素
    public boolean contains(int data) {
        for(int i = 0; i < usedSize; i++) {
            if(array[i] == data) {
                return true;
            }
        }
        return false;
    }


    //查找元素data在顺序表中的下标位置
    public int indexOf(int data) {
        for(int i = 0; i < usedSize; i++) {
            if(array[i] == data) {
                return i;
            }
        }
        return -1;
    }


    //获取下标某元素
    public int get(int pos) {
        if(isEmpty()) {
            System.out.println("顺序表为空，无法获取元素");
            return -1;
        }

        if(checkPos(pos)) {
            System.out.println("获取下标超出范围，获取失败");
            return -1;
        }
        System.out.print(pos + "下标元素为->");
        return array[pos];

    }

    public void set(int pos, int value) {
        if(checkPos(pos)) {
            System.out.println("位置不合法");
            return;
        }
        array[pos] = value;
    }

    //删除元素value
    public void remove(int value) {
        int index = indexOf(value);
        if(index == -1) {
            System.out.println("没有此元素");
            return;
        }

        for(int i = index; i < usedSize - 1; i++) {
            array[i] = array[i+1];
        }
        usedSize--;
    }

    public int size() {
        return usedSize;
    }

    public void clear() {
        usedSize = 0;
    }

    public void display() {
        for(int i = 0; i < usedSize; i++) {
            System.out.print(array[i] + "->");
        }
        System.out.println();
    }

}
